<?php
require_once("config.php");
// 专门用来写封装函数的文件
header("Content-Type:text/html;charset=utf-8");

//添加
$pre_ = "pre_";
function insert($tabName,$filed,$value){
    // 引入全局变量
    global $connect;
    global $pre_;
    // 书写sql语句 
    $sql = "INSERT INTO {$pre_}{$tabName} (`nickname`,`mobile`,`depid`,`jobid`) VALUES ('小黄','12903245','2','2')";
    // 执行这个语句返回一个字符串
    $res =  @mysqli_query($connect,$sql);
    // 判断查询语句是否正确
    if(!$res){
        echo "【sql执行错误】:".mysqli_error($connect);
        exit;
    }
    // 获取自增主键 返回最后一个查询中自动生成的 ID     
    return mysqli_insert_id($connect);
}
// $insert =  insert();
// echo $insert;

//修改
function update($tabName,$filed,$where){
    global $connect;
    global $pre_;
    $sql = "UPDATE {$pre_}{$tabName} SET `nickname` = '神刀夜狗' WHERE id > 34";
    $res = mysqli_query($connect,$sql);
    if(!$res){
        echo "【sql执行错误】:".mysqli_error($connect);
        exit;
    }
    //返回操作成功的行数
    $rows = mysqli_affected_rows($connect);
    return $rows;
}
// $rows = update();
// echo $rows;
//删除
function delete($tabName,$where){
    global $connect;
    global $pre_;
    $sql = "DELETE FROM {$pre_}{$tabName} WHERE `nickname` = ?";
    $res = mysqli_query($connect,$sql);

    if(!$res){
        echo "【sql执行错误】:".mysqli_error($connect);
        exit;
    }
    return mysqli_affected_rows($connect);
}
// $rows = delete();
// echo $rows;


// localhost
//单查询
function select($tabName){
    global $connect;
   
    global $pre_;
    //单查询
    $sql = "SELECT * FROM {$pre_}{$tabName}";
    $res = mysqli_query($connect,$sql);
    if(!$res){
        echo "【sql执行错误】:".mysqli_error($connect);
        exit;
    }
    //返回关联数组对象
    $data = [];
    //使用while循环来拿数据  $rows = mysqli_fetch_assoc( $res) 每次拿一挑数据 直到拿到最后一条数据停
    while($rows = mysqli_fetch_assoc( $res))
    {
        $data[] = $rows;
    }
    return $data;
}
// $arr = select();
// var_dump($arr) ;

//多表查询
function selectAll(){
    global $connect;
    global $pre_;
    $sql = "SELECT person.*,dept.name AS deptname,job.name AS jobname FROM {$pre_}person AS person LEFT JOIN {$pre_}department AS dept ON dept.id = person.depid LEFT JOIN {$pre_}job AS job ON job.id = person.jobid";
    $res = mysqli_query($connect,$sql);
    if(!$res){
        echo "【sql执行错误】:".mysqli_error($connect);
        exit;
    }
    //返回关联数组对象
    $data = [];
    //使用while循环来拿数据  $rows = mysqli_fetch_assoc( $res) 每次拿一挑数据 直到拿到最后一条数据停
    while($rows = mysqli_fetch_assoc( $res))
    {
        $data[] = $rows;
    }
    return $data;
}